package com.cheetah.advice;

import com.cheetah.builder.ResultBuilder;
import com.cheetah.exceptions.CommonError;
import com.cheetah.builder.Result;
import com.cheetah.exceptions.CheetahException;
import com.cheetah.exceptions.CheetahRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;

/**
 * @Author Administrator
 * @Date 2019/10/10
 * @Version V1.0
 * @Description:
 **/
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(HttpServletResponse resp, Exception e) {
        log.error(e.getMessage());

        if(e instanceof CheetahException ){
            CheetahException ce = (CheetahException)e;
            return ResultBuilder.builder().fail(ce.getErrorCode() == 0 ? CommonError.ERROR_CODE_500.getErrorCode() : ce.getErrorCode(),
                    ce.getMessage());
        }

        if(e instanceof CheetahRuntimeException ){
            CheetahRuntimeException ce = (CheetahRuntimeException)e;
            return ResultBuilder.builder().fail(ce.getErrorCode() == 0 ? CommonError.ERROR_CODE_500.getErrorCode() : ce.getErrorCode(),
                    ce.getMessage());
        }
        return ResultBuilder.builder().fail(CommonError.ERROR_CODE_500.getErrorCode(),e.getMessage());
    }
}
